package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie工具类
 */
public class CookieUtil {

    /**
     * 添加cookie
     * @param name
     * @param value
     * @param time
     * @param resp
     */
    public static void addCookie(String name, String value, int time,HttpServletResponse resp){
        //8：创建cookie对象，
        //注意：设置cookie存活时间：30分钟 /共享路径
        Cookie c =  new Cookie(name, value);
        //存活时间：30分钟
        c.setMaxAge(time);
        //共享路径
        c.setPath("/");
        //9：使用response对象将cookie对象传输到浏览器中
        resp.addCookie(c);
    }
    public static String getToken(HttpServletRequest req, HttpServletResponse resp){
        //获取cookie信息
        String token = null;
        Cookie[] cookies = req.getCookies();
        if(cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                if("token".equals(cookie.getName())){
                    token = cookie.getValue();
                    //延长cookie的时间
                    cookie.setMaxAge(RedisKeys.USER_LOGIN_TOKEN.getTime().intValue());
                    resp.addCookie(cookie);
                    break;
                }
            }
        }
        return token;
    }
}
